<template>
  <div class="app-container">
    <!-- 按钮 -->
    <el-button type="primary" size="small" @click="onclickLizhiApply">离职申请</el-button>

    <!-- 说明 -->
    <!-- <span style="padding-left: 10px;">
      <el-tag type="warning" style="padding-left: 10px;">配置说明：删除某个部门时，必须保证下属部门和当前部门人数均为0！</el-tag>
    </span> -->
    <!-- {{list}} -->
    <div style="padding: 10px;" />

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      stripe
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0 && scope.row.chexiao==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1 && scope.row.chexiao==0" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==2 && scope.row.chexiao==0" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.chexiao==1" type="info">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="工号" align="center">
        <template slot-scope="scope">
          {{ scope.row.uid }}
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column label="离职时间" align="center">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.lizhiDate) }}
        </template>
      </el-table-column>
      <el-table-column label="工作接收人" align="center">
        <template slot-scope="scope">
          {{ scope.row.receiverN }}
        </template>
      </el-table-column>
      <el-table-column label="工作交接" align="center">
        <template slot-scope="scope">
          {{ scope.row.jobDesc }}
        </template>
      </el-table-column>
      <el-table-column label="物资交接" align="center">
        <template slot-scope="scope">
          {{ scope.row.itemDesc }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id)">详情 </el-button>
          <el-button v-if="scope.row.sta>0 && scope.row.chexiao == 0" size="mini" type="primary" plain @click="printPdf(scope.row.id)">生成PDF </el-button>
          <el-button v-if="(scope.row.chexiao == 0)" size="mini" type="danger" plain @click="revertApply(scope.$index)">撤回 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <!-- 对话框 -->
    <el-dialog width="40%" :visible.sync="lizhiApplyDialog.visible" top="5vh" center :show-close="false">
      <el-form ref="form" size="mini" label-position="left" label-width="100px">
        <el-row>
          <!-- 左侧 -->
          <el-col :span="11">
            <div class="title"><i class="el-icon-document" /> 申请单</div>
            <el-form-item label="工号">
              {{ userInfo.uid }}
            </el-form-item>
            <el-form-item label="姓名">
              {{ userInfo.name }}
            </el-form-item>
            <el-form-item label="离职时间">
              <el-date-picker v-model="lizhiApplyDialog.lizhiDate" type="date" placeholder="选择离职日期" style="width: 100%;" />
            </el-form-item>

            <el-form-item label="交接人">
              <el-cascader v-model="lizhiApplyDialog.receiver" :options="userList" clearable style="width: 100%;" @change="jiaojierenChange" />
            </el-form-item>

            <el-form-item label="工作交接">
              <el-input v-model="lizhiApplyDialog.jobDesc" type="textarea" :rows="4" placeholder="请详细列明需要交接的工作项目" />
            </el-form-item>
            <el-form-item label="物资交接">
              <el-input v-model="lizhiApplyDialog.itemDesc" type="textarea" :rows="4" placeholder="请详细列明需要交接的物品" />
            </el-form-item>

          </el-col>
          <!-- 右侧 -->
          <el-col :span="11" :offset="2">
            <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
            <div v-for="(item,index) in lizhiApplyDialog.auditors" :key="index">
              <!-- 箭头：第一个不显示 -->
              <div v-if="index>0" class="step-arrow">
                <el-row>
                  <el-col :span="8">
                    <div><i class="el-icon-caret-bottom" /></div>
                  </el-col>
                </el-row>
              </div>
              <!-- 步骤样式 -->
              <div class="step">
                <el-row>
                  <el-col :span="8">
                    <div class="step-info-left">{{ item.stepName || item.positionName }}</div>
                  </el-col>
                  <el-col :span="16">
                    <div class="step-info-right">{{ item.name }}</div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="lizhiApplyDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="clickApply">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <lizhi-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  websock
} from '@/websock'
import { quchongAuditors } from '@/utils/utils'
import moment from 'moment'
import LizhiDetail from '../../components/details/lizhiDetail.vue'

export default {
  components: { LizhiDetail },
  data() {
    return {
      list: [],
      userList: [],
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      userInfo: {},
      listLoading: false,
      auditors: [],
      lizhiApplyDialog: {
        visible: false,
        userName: '',
        uid: '',
        receiver: [],
        jobDesc: '',
        itemDesc: '',
        lizhiDate: '',
        auditors: []
      },
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async mounted() {
    this.userInfo = await websock.getUserInfo()

    websock.getDepartList().then((data) => {
      this.departmentList = data
    })
    websock.getPosList().then((data) => {
      this.positionList = data
    })

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + '',
        label: res[i].name,
        children: []
      })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          label: res[i].userList[j].name,
          value: JSON.stringify({ uid: res[i].userList[j].uid, name: res[i].userList[j].name })
        })
      }
    }
    this.userList = userList

    this.getApplyRecord()

    this.auditors = await websock.getAuditors({ typ: 5 })
    quchongAuditors(this.auditors)
    console.log('auditors', this.auditors)

    this.lizhiApplyDialog.auditors = this.auditors.slice()
  },
  methods: {
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = 'MM-DD HH:mm') {
      return moment(stamp).format(str)
    },
    async getApplyRecord() {
      this.listLoading = true
      const data = await websock.departureApplyRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      })
      this.listLoading = false
      this.list = data.list
      this.dataTotal = data.count
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getApplyRecord()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getApplyRecord()
    },
    async onclickLizhiApply() {
      this.lizhiApplyDialog.visible = true
      this.lizhiApplyDialog.receiver = []
      this.lizhiApplyDialog.jobDesc = ''
      this.lizhiApplyDialog.itemDesc = ''
      this.lizhiApplyDialog.lizhiDate = ''
    },
    async clickApply() {
      if (!this.lizhiApplyDialog.lizhiDate) return this.$message.error('请选择离职时间')
      if (!this.lizhiApplyDialog.jobDesc) return this.$message.error('请输入工作交接内容')
      if (!this.lizhiApplyDialog.itemDesc) return this.$message.error('请输入物品交接内容')
      if (this.lizhiApplyDialog.receiver.length == 0) return this.$message.error('请选择交接人')
      if (this.lizhiApplyDialog.auditors.length == 0) return this.$message.error('请选择审核人')

      const auditors = []
      for (let i = 0; i != this.lizhiApplyDialog.auditors.length; i++) {
        auditors.push({ uid: this.lizhiApplyDialog.auditors[i].uid, stepName: this.lizhiApplyDialog.auditors[i].stepName || this.lizhiApplyDialog.auditors[i].positionName })
      }

      try {
        await websock.departureApply({
          name: this.userInfo.name,
          lizhiDate: this.lizhiApplyDialog.lizhiDate,
          jobDesc: this.lizhiApplyDialog.jobDesc,
          itemDesc: this.lizhiApplyDialog.itemDesc,
          receiver: JSON.parse(this.lizhiApplyDialog.receiver[1]).uid,
          receiverName: JSON.parse(this.lizhiApplyDialog.receiver[1]).name,
          auditors
        })

        this.$message.success('提交成功，等待审核')

        this.lizhiApplyDialog.visible = false

        this.getApplyRecord()
      } catch (err) {
        this.$message.error(err.message || 'error')
      }
    },
    jiaojierenChange() {
      // console.log('jiaojieren change', this.lizhiApplyDialog)

      // let audi = []
      // audi = this.auditors.slice()
      // if (this.lizhiApplyDialog.receiver[1] != null) {
      //   const jiaoren = JSON.parse(this.lizhiApplyDialog.receiver[1])
      //   audi.unshift({ uid: jiaoren.uid, stepName: '工作交接人', name: jiaoren.name })
      //   console.log('auditors1', audi)
      //   this.lizhiApplyDialog.auditors = audi.slice()
      //   console.log('auditors2', this.lizhiApplyDialog.auditors)
      // }
    },
    async revertApply(idx) {
      try {
        await websock.revertDepartureApply({
          id: this.list[idx].id
        })
        this.list[idx].sta = 4
        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({
          title: err.message || 'error'
        })
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
    },
    printPdf(id) {
      websock.printPdf({ typ: 5, id }).then(res => {
        console.log('print pdf', res)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = res
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import url("../../styles/form.css");
</style>
